﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;

namespace MixingStation
{
    public partial class WeightShowUC : UserControl
    {
        private SerialPort m_SerialPort = null;
        private WeightParameter m_WeighParameter = null;

        public WeightShowUC()
        {
            InitializeComponent();
        }

        //初始化地秤
        public void InitWeightShowUC(WeightParameter weightParameter)
        {
            m_WeighParameter = weightParameter;
            try
            {
                m_SerialPort = new SerialPort(weightParameter.DCCom, weightParameter.DCPort, Parity.None, 8, StopBits.One);
                m_SerialPort.DataReceived += m_SerialPort_DataReceived;
                m_SerialPort.Open();
            }
            catch (Exception ex)
            {
                this.txtWeightShow.BackColor = Color.Red;
                LogHelper.error("初始化地磅端口" + weightParameter.DCCom + "异常：" + ex.Message);
            }
        }

        //获取当前显示重量
        public decimal GetCurrentWeight()
        {
            if (string.IsNullOrEmpty(txtWeightShow.Text))
                return 0;
            decimal currentWeight = Convert.ToDecimal(this.txtWeightShow.Text.Trim());
            return currentWeight;
        }

        //判断是否稳定
        public bool IsWeightStable()
        {
            if (this.lblStatus.Text == "稳定")
                return true;
            else
                return false;
        }

        private delegate void myWeightDelegate(string s);
        void m_SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            System.Threading.Thread.Sleep(200);
            try
            {
                byte[] readBuffer = new byte[m_SerialPort.ReadBufferSize];
                if (readBuffer.Length <= 0)
                    return;
                m_SerialPort.Read(readBuffer, 0, readBuffer.Length);
                string readstr = "";
                if (m_WeighParameter.DCType == 0)
                    readstr = CommonHelper.ByteToHexStr(readBuffer);
                else if (m_WeighParameter.DCType == 1)
                    readstr = Encoding.UTF8.GetString(readBuffer);
                else if (m_WeighParameter.DCType == 2)
                    readstr = Encoding.UTF8.GetString(readBuffer);
                else if (m_WeighParameter.DCType == 3)
                    readstr = Encoding.UTF8.GetString(readBuffer);
                else if (m_WeighParameter.DCType == 4)
                    readstr = CommonHelper.ByteToHexStr(readBuffer);
                else if (m_WeighParameter.DCType == 5)
                    readstr = CommonHelper.ByteToHexStr(readBuffer);
                this.Invoke(new myWeightDelegate(ReadWeight), readstr.TrimEnd());
            }
            catch (Exception ex)
            {
                LogHelper.error("获取地秤" + m_WeighParameter.DCCom + "数据异常：" + ex.Message);
            }
        }

        private int index = 0;
        private void ReadWeight(string str)
        {
            int num = m_WeighParameter.CompareTimes;
            int weight = 0;
            //金塔地磅解析、鑫达其中一种老称和惠塔原料称
            if (m_WeighParameter.DCType == 0)
            {
                weight = GetWeightFirstWay(str.Trim());
            }
            //福塔地磅解析
            else if (m_WeighParameter.DCType == 1)
            {
                weight = GetWeightSecondWay(str.Trim());
            }
            //鑫达进出厂称解析
            else if (m_WeighParameter.DCType == 2)
            {
                weight = GetWeightThirdWay(str.Trim());
            }
            //金塔新的地秤
            else if (m_WeighParameter.DCType == 3)
            {
                weight = GetWeightFourWay(str.Trim());
            }
            else if (m_WeighParameter.DCType == 4)
            {
                weight = GetWeightFiveWay(str.Trim());
            }
            else if (m_WeighParameter.DCType == 5)
            {
                weight = GetWeightSixWay(str.Trim());
            }
            if (weight == -1)
                return;
            //稳定性判断
            if (int.Parse(txtWeightShow.Text) == weight)
                index++;
            else
                index = 0;
            if (index >= num)
            {
                lblStatus.Text = "稳定";
                lblStatus.ForeColor = Color.ForestGreen;
            }
            else
            {
                lblStatus.Text = "";
            }
            this.txtWeightShow.Text = weight.ToString();
        }

        //金塔地磅解析、鑫达其中一种老称、惠塔原料地秤
        private int GetWeightFirstWay(string str)
        {
            if (str.IndexOf("4753AC") < 0 || str.Length < str.IndexOf("4753AC") + 24)
                return -1;
            string subStr = str.Substring(str.IndexOf("4753AC"), 24);
            if (!subStr.EndsWith("EB"))
                return -1;
            string dataSubStr = subStr.Substring(10, 12);
            string signStr = subStr.Substring(6, 2);
            //计算重量
            int weight = int.Parse(dataSubStr.Substring(1, 1) + dataSubStr.Substring(3, 1) + dataSubStr.Substring(5, 1)
                + dataSubStr.Substring(7, 1) + dataSubStr.Substring(9, 1) + dataSubStr.Substring(11, 1));
            //2B为正数，2D为负数
            if (signStr == "2D")
                weight = -weight;
            return weight;
        }

        //福塔地秤数据解析格式
        private int GetWeightSecondWay(string str)
        {
            if (str.IndexOf("ST,GS,") < 0 && str.IndexOf("US,GS,") < 0)
                return -1;
            if (str.Length < str.IndexOf("ST,GS,") + 15
                && str.Length < str.IndexOf("US,GS,") + 15)
                return -1;
            string subStr = "";
            if (str.IndexOf("ST,GS,") >= 0)
                subStr = str.Substring(str.IndexOf("ST,GS,"), 15);
            else if (str.IndexOf("US,GS,") >= 0)
                subStr = str.Substring(str.IndexOf("US,GS,"), 15);
            if (!subStr.EndsWith("t") && !subStr.EndsWith("T")
                && !subStr.EndsWith("K") && !subStr.EndsWith("k"))
                return -1;
            int weight = int.Parse(subStr.Substring(6, 8));
            return weight;
        }

        //鑫达进出厂称解析
        private int GetWeightThirdWay(string str)
        {
            char[] ret = str.ToCharArray();
            string dataStr = string.Concat<char>(ret.Reverse<char>());
            if (dataStr.IndexOf("=") < 0)
                return -1;
            if (dataStr.Length < dataStr.IndexOf("=") + 9)
                return -1;
            string subStr = dataStr.Substring(dataStr.IndexOf("="), 9);
            if (!subStr.EndsWith("."))
                return -1;
            string weightStr = subStr.Substring(subStr.IndexOf("=") + 1, 7);
            int weight = int.Parse(weightStr);
            return weight;
        }

        //金塔换了地秤
        private int GetWeightFourWay(string str)
        {
            char[] ret = str.ToCharArray();
            string dataStr = string.Concat<char>(ret.Reverse<char>());
            if (dataStr.IndexOf("=") < 0)
                return -1;
            if (dataStr.Length < dataStr.IndexOf("=") + 8)
                return -1;
            string subStr = dataStr.Substring(dataStr.IndexOf("="), 8);
            if (!subStr.EndsWith("."))
                return -1;
            string weightStr = subStr.Substring(subStr.IndexOf("=") + 1, 6);
            int weight = int.Parse(weightStr);
            return weight;
        }

        //惠塔换了新称
        private int GetWeightFiveWay(string str)
        {
            if (str.IndexOf("02") < 0 || str.Length < str.IndexOf("02") + 24)
                return -1;
            string subStr = str.Substring(str.IndexOf("02"), 24);
            if (!subStr.EndsWith("03"))
                return -1;
            string dataSubStr = subStr.Substring(4, 12);
            string signStr = subStr.Substring(2, 2);
            //计算重量
            int weight = int.Parse(dataSubStr.Substring(1, 1) + dataSubStr.Substring(3, 1) + dataSubStr.Substring(5, 1)
                + dataSubStr.Substring(7, 1) + dataSubStr.Substring(9, 1) + dataSubStr.Substring(11, 1));
            //2B为正数，2D为负数
            if (signStr == "2D")
                weight = -weight;
            return weight;
        }

        private int GetWeightSixWay(string str)
        {
            if (str.IndexOf("02") < 0 || str.Length < str.IndexOf("02") + 36)
                return -1;
            string subStr = str.Substring(str.IndexOf("02"), 36);
            if (!subStr.EndsWith("0D80"))
                return -1;
            string dataSubStr = subStr.Substring(10, 10);
            //计算重量
            int weight = int.Parse(dataSubStr.Substring(1, 1) + dataSubStr.Substring(3, 1) + dataSubStr.Substring(5, 1)
                + dataSubStr.Substring(7, 1) + dataSubStr.Substring(9, 1));
            return weight;
        }

        public delegate void WeightTextChangedEventHandler(object sender, EventArgs e);
        public event WeightTextChangedEventHandler WeightTextChangedEvent;
        private void txtWeightShow_TextChanged(object sender, EventArgs e)
        {
            if (this.lblStatus.Text != "稳定")
                return;
            if (WeightTextChangedEvent != null)
            {
                WeightTextChangedEvent(sender, e);
            }
        }

        //稳定状态变化的时候触发重量变化事件，由于当重量变化后称重未稳定，导致界面皮重不刷新，
        private void lblStatus_TextChanged(object sender, EventArgs e)
        {
            if (this.lblStatus.Text != "稳定")
                return;
            if (WeightTextChangedEvent != null)
            {
                WeightTextChangedEvent(sender, e);
            }
        }
    }
}
